﻿var EmployeeGrid = EmployeeGrid || {};
EmployeeGrid = function () {
    var offsetMiliseconds = new Date().getTimezoneOffset() * 60000;
    var gridInEditMode = false;
    var scratchDropDownChanged = false;
    var EmployeeGridDatasource = new kendo.data.DataSource({
        transport: {
            read: {                 
                url: "/EmployeeGrid/GetEmployees",
                type: "get",                 
                dataType: 'json',
            },
            create: {
            
                type: "POST",
                url: "/EmployeeGrid/CreateEmployee",
                contentType: "application/json",
                dataType: 'json',
                error: function (request, status, error) {
                    debugger;
                            alert(request.responseText);
                        }
             
                   
            },

            update: {
                
                type: "POST",
                url: "/EmployeeGrid/UpdateEmployee",
                contentType: "application/json",
                dataType: 'json'
            },
         
            destroy: {             
                    type: "POST",
                    url: "../EmployeeGrid/DeleteEmployee",
                    contentType: "application/json; charset=utf-8",
                    dataType: 'json',
                    //data: JSON.stringify({ id: options.data.id }),

                    //success: function (data) {
                    //    options.success(data);
                    //},
                    //error: function (request, status, error) {
                    //    debugger;
                    //    alert(request.responseText);
                    //}

            },
               
            parameterMap: function (options) {
                return kendo.stringify(options); // kendo.stringify serializes to JSON string
            }

   

        },
        pageSize: 5,
        schema: {
            model: {
                id: "id",
                fields: {
                    id: {
                        editable: false, nullable: true,
                        type: "int"
                    },
                    hireDate: {
                        type: "date",
                        //  validation: { required: true },
                        nullable: true,
                        value: "",
                        defaultOption: null
                    },
                    terminationDate: {
                        type: "date",
                        //  validation: { required: true },
                        nullable: true,
                        value: "",
                        defaultOption: null
                    },

                    contactId: {
                        type: "int"
                        // defaultValue: contactId
                    },

                    department: {
                        type: "int"
                    },

                    departmentId: {
                        type: "int",
                         defaultValue: 0
                    },

                    salary: {
                        type: "int"
                    },

                    cName: {
                        type: "string"
                    },
                    depname: {
                        type: "string"
                    },

                    notes:
                        {
                            type: "string"
                        },


                    skills:
                       {
                           type: "string"
                       },

                    description:
                        {
                            type:"string"
                        },
                    contactId:
                        {
                            type:"int",
                            defaultValue: 0
                        },
                    
                   

                    error: function (a) {
                        debugger;
                        $('#EmployeeGrid').data("kendoGrid").cancelChanges();
                    },

                }
            }
        }
    });
  

    var allContactsforEmployeedatasource = new kendo.data.DataSource({    
        transport: {
        read: {
        url: "/CommunicationMessageGrid/GetAllContacts/",
        type: "get",
        contentType: "application/json",
    dataType: "json"
}
    }
    });
    var departmentdataSource = new kendo.data.DataSource({
     
        transport: {
        read: {
        url: "/ProductRequestGrid/GetDepartments/",
        type: "get",
        contentType: "application/json",
    dataType: "json"
}
    }
    });

    return {
        EmployeeGridDatasource: EmployeeGridDatasource,
        gridInEditMode: gridInEditMode,
        allContactsforEmployeedatasource: allContactsforEmployeedatasource,
        departmentdataSource: departmentdataSource,

        scratchDropDownChanged: scratchDropDownChanged
    }
}();




$(function () {
    
    $(window).on("beforeunload", function () {

        if (InvoiceGrid.gridInEditMode) {
            return "Are you sure you want to discard all your changes."
        }

    });
  
   
    function dateTimeEditor(container, options) {
        $('<input data-text-field="' + options.field + '" data-value-field="' + options.field + '" data-bind="value:' + options.field + '" data-format="' + options.format + '"/>')
        .appendTo(container)
        .kendoDateTimePicker({});
    }
    $("#EmployeeGrid").kendoGrid({
        dataSource: EmployeeGrid.EmployeeGridDatasource,
      
        scrollable: true,
        height: "250px",
        toolbar: [{ name: "create", text: "Add an Emoloyee" }, "excel"], //, "save", "cancel"],
        excel: {
            fileName: "EmployeeExport.xlsx"
        },
        pageable: true,
        height: 300,

        columns: [
             { title: "projects", filterable: false, width: "8em", template: "<a onclick=\"showEmployeeProjects('#=id #',this);\"style=\"cursor: pointer;\"> View</a>" },
{ field: "contactname", title: "AllContacts *", filterable: false, width: "8em", editor: allcontactsDropdownEditor, editable: true },


        {
            field: "hireDate", title: " Hire Date *", width: "10em", filterable: false, format: "{0:MM/dd/yyyy HH:mm tt}",
            editor: dateTimeEditor,
            filterable: {
                ui: "datetimepicker"
            }
        },

          {
              field: "terminationDate", title: " Termination Date", width: "10em", filterable: false, format: "{0:MM/dd/yyyy HH:mm tt}",
              editor: dateTimeEditor,
              filterable: {
                  ui: "datetimepicker"
              }
          },
 { field: "depCode", title: "Department *", hidden: true, editor: departmentDropDownEditor, filterable: false, width: "10em" },
         { field: "salary", title: "Salary", filterable: true, width: "8em" },



        { field: "skills", title: "Skills", filterable: true, width: "8em" },

           { field: "notes", title: "Notes", filterable: true, width: "8em" },

      {
          title: "&nbsp;",
          width: "25em",
          //command: ["edit", "destroy"]
          command: [

              "edit",
              {
                  name: "Delete",


                  click: function (e) {

                      var tr = $(e.target).closest("tr"); //get the row for deletion
                      var dataItem = this.dataItem(tr); //get the row data so it can be referred later
                      //see what is coming in dataItem
                      //if (dataItem > 0) {
                      //    $("#delValidation").addClass('in')
                      //}
                      //else {

                      deleteTopicConfirmation(e, this);
                      ////}
                      return false;
                  }
              }
          ]
      }
        ],
        filterable: {
            extra: false,
            operators: {
                string: {
                    eq: "Is equal to",
                    neq: "Is not equal to",
                    contains: "Contains"
                }
            }
        },

        editable: "popup",
        sortable: {
            mode: "single",
            allowUnsort: false
        },
        selectable: true,

        cancel: function () {
            EmployeeGrid.gridInEditMode = false;
        },
        excelExport: function (e) {
            for (var i = 0; i < e.workbook.sheets[0].columns.length; i++) {
                e.workbook.sheets[0].columns[i].autoWidth = true;
            }
        }
    });

    EmployeeGrid.EmployeeGridDatasource.bind("requestEnd", showSuccessMessage);


    function showSuccessMessage(e) {
        if (e.type === "update" || e.type === "create") {
            EmployeeGrid.gridInEditMode = false;
            $("#saveConfirm").addClass('in');
            e.sender.read();
        }
    }

    function onRequestEnd(e) {
        debugger;
        if (e.response.Data && e.response.Data.length) {
            var persons = e.response.Data;
            if (this.group().length) {
                for (var i = 0; i < persons.length; i++) {
                    var gr = persons[i];
                    if (gr.Member == "HireDate") {
                        gr.Key = gr.Key.replace(/\d+/,
                            function (n) { return parseInt(n) + offsetMiliseconds }
                        );
                    }
                    addOffset(gr.Items);
                }
            } else {
                addOffset(persons);
            }

        }
    }

    function addOffset(persons) {
        for (var i = 0; i < persons.length; i++) {
            persons[i].BirthDate = persons[i].HireDate.replace(/\d+/,
                function (n) { return parseInt(n) + offsetMiliseconds }
            );
        }
    }

    $(".close").click(function () {
        $(this).parent().removeClass('in');
    });
    function deleteTopicConfirmation(e, widget) {
        var grid = $('#EmployeeGrid').data("kendoGrid");
        deleteConfirmation(e, widget, grid);
    }

    function deleteConfirmation(e, widget, grid) {

        var currentRow = $(e.target).closest("tr"); //get the row for deletion

        var currentRowData = widget.dataItem(currentRow); //get the row data so it can be  referred later

        var kendoWindow = $("<div />").kendoWindow({

            title: "Confirmation",
            resizable: true,
            modal: true,
            width: "400px"
        });

        kendoWindow.data("kendoWindow")

            .content($("#delete-confirmation").html())

            .center().open();

        kendoWindow

            .find(".delete-confirm,.delete-cancel")
            .click(function () {
                if ($(this).hasClass("delete-confirm")) {

                    grid.dataSource.remove(currentRowData);

                    grid.dataSource.sync();

                }

                $(this).closest("[data-role=window]").kendoWindow("close");

            });

    }

    function allcontactsDropdownEditor(container, options) {
        $('<input data-text-field="contactname"  data-value-field="id"   data-bind="value:contactId"/>').appendTo(container).kendoDropDownList({
            
                autoBind: true,
             
                dataSource: EmployeeGrid.allContactsforEmployeedatasource,
            });
    }
    function departmentDropDownEditor(container, options) {

        //$('<input required="required" name="State" data-text-field="stateName" data-value-field="id" data-bind="value:stateId"/>').appendTo(container).kendoDropDownList({
        //    autoBind: true,
        $('<input  data-text-field="depCode" data-value-field="id" data-bind="value:departmentId"/>').appendTo(container).kendoDropDownList({
            autoBind: true,
           
            dataSource: EmployeeGrid.departmentdataSource

        });
    }
   

});